package sUtils;

import javax.microedition.io.*;
import javax.microedition.io.file.*;
import java.io.*;

public class File {

    FileConnection h_file=null;
    DataOutputStream h_out=null;
    DataInputStream h_in=null;


    static public String normFileName( String name )
    {
        return name.startsWith("file://") ? name : ("file://"+name);
    }


    public boolean create( String name )
    {
        close();
        try {
            h_file = (FileConnection) Connector.open(normFileName(name));
            if (h_file!=null) 
            {
                if (h_file.exists()) h_file.truncate(0); else h_file.create();
                h_out = h_file.openDataOutputStream();
            }
        } catch( Exception e ) {}
        return h_out!=null;
    }

    public boolean open( String name )
    {
        close();
        try {
            h_file = (FileConnection) Connector.open(normFileName(name));
            if (h_file!=null)
            {
                if (h_file.exists()) h_in = h_file.openDataInputStream(); else
                {
                    h_file.close(); h_file=null;
                }
            }
        } catch( Exception e ) {}
        return h_out!=null;
    }

    public void close()
    {
        try {
            if (h_in!=null) h_in.close();
            if (h_out!=null) h_out.close();
            if (h_file!=null) h_file.close();
        } catch (Exception e){ } finally { h_file=null; h_out=null; h_in=null; }
    }

    public boolean opened()
    {
        return h_file!=null && (h_in!=null || h_out!=null);
    }

    public boolean writeStr( String s )
    {
        if (h_out!=null && s!=null) try {
            h_out.write(s.getBytes(),0,s.length());
            return true;
        } catch( IOException e ) {}
        return false;
    }

    public boolean writeBytes( byte[] b, int len )
    {
        if (h_out!=null && b!=null && len>0) try {
            h_out.write(b, 0, len);
            return true;
        } catch( IOException e ) {}
        return false;
    }

    public String readLine()
    {
        if (h_in!=null) try {
            StringBuffer sb = new StringBuffer(64); byte b;
            while (h_in.available()>0)
            {
                b = h_in.readByte();
                if (b=='\n') return sb.toString(); else
                if (b!='\r') sb.append((char)(int)b);
            }
            return sb.toString();
        } catch( IOException e ) {}
        return null;
    }


}
